package com.tozed.android.launcher.simpleui;

import java.util.ArrayList;
import java.util.List;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.util.Log;

public class SimpleAllAppsList
{
	private static final String TAG = "SimpleAllAppsList ";
	public static final int DEFAULT_APPLICATIONS_NUMBER = 42;
	
	// 所有应用对应的List
	public ArrayList<SimpleApplicationInfo> data = new ArrayList<SimpleApplicationInfo>(DEFAULT_APPLICATIONS_NUMBER);
		
	// 从最后一次notify()调用后,所有被添加的 APP
	public ArrayList<SimpleApplicationInfo> added = new ArrayList<SimpleApplicationInfo>(DEFAULT_APPLICATIONS_NUMBER);
	
	// 从最后一次notify()调用后,所有被删除的 APP
	public ArrayList<SimpleApplicationInfo> removed = new ArrayList<SimpleApplicationInfo>();
	
	// 从最后一次notify()调用后,所有被修改的 APP
	public ArrayList<SimpleApplicationInfo> modified = new ArrayList<SimpleApplicationInfo>();
	
	// 默认的应用图标
	private SimpleIconCache mIconCache;
	
	public SimpleAllAppsList(SimpleIconCache iconCache){
		mIconCache = iconCache;
	}
	
	// 添加应用到所有列表中
    public void add(SimpleApplicationInfo info) {
        if (findActivity(data, info.componentName)) {
            return;
        }
        
        data.add(info);
        added.add(info);
    }
	
	public void clear()
	{
		data.clear();
        added.clear();
        removed.clear();
        modified.clear();
	}
	
	// 在给定的包名中查询含MAIN/LAUNCHER的所有的activity
    private static List<ResolveInfo> findActivitiesForPackage(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();

        final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        mainIntent.setPackage(packageName);

        final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
        return apps != null ? apps : new ArrayList<ResolveInfo>();
    }
    
    private static boolean findActivity(List<ResolveInfo> apps, ComponentName component) {
        final String className = component.getClassName();
        for (ResolveInfo info : apps) {
            final ActivityInfo activityInfo = info.activityInfo;
            if (activityInfo.name.equals(className)) {
                return true;
            }
        }
        return false;
    }
    
    // 根据ComponentName是否能查到对应的app
    private static boolean findActivity(ArrayList<SimpleApplicationInfo> apps, ComponentName component) {
    	 final int N = apps.size();
         for (int i=0; i<N; i++) {
             final SimpleApplicationInfo info = apps.get(i);
             if (info.componentName.equals(component)) {
                 return true;
             }
         }
         return false;
    }
    
    // 根据给定的包名和类名查找应用对象
    private SimpleApplicationInfo findApplicationInfoLocked(String packageName, String className) {
        for (SimpleApplicationInfo info: data) {
            final ComponentName component = info.intent.getComponent();
            if (packageName.equals(component.getPackageName())
                    && className.equals(component.getClassName())) {
                return info;
            }
        }
        return null;
    }
    
    // 根据包名添加图标
    public void addPackage(Context context, String packageName) {
        final List<ResolveInfo> matches = findActivitiesForPackage(context, packageName);

        if (matches.size() > 0) {
            for (ResolveInfo info : matches) {
            	ComponentName componentName = new ComponentName(packageName, info.activityInfo.name);
            	//if (HiddenIconsManager.getInstance().isHiddenIcon(componentName))
            	//	continue;
            	SimpleApplicationInfo appInfo = new SimpleApplicationInfo(context.getPackageManager(), info, mIconCache, null);
            	//if (!findActivity(SimpleLauncherModel.sDownloadApps, appInfo.componentName));
                add(appInfo);
            }
        }
    }
    
    // 刷新删除的快捷方式
    private void refreshDelShortcut(ArrayList<SimpleApplicationInfo> apps, String pkgName, 
    		ResolveInfo resolveInfo, Context context)
    {
      SimpleApplicationInfo app = (SimpleApplicationInfo)apps.get(0);
      
      app.componentName = new ComponentName(pkgName, resolveInfo.activityInfo.name);
      app.intent.setComponent(app.componentName);
      app.intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
      apps.remove(app);
      
      mIconCache.remove(app.componentName);
      mIconCache.getTitleAndIcon(app, resolveInfo, null);
      modified.add(app);
      
      SimpleLauncherModel.updateItemInDatabaseHelper(context, new ContentValues(), app);
    }
    
    // 从给定的apk的包名中删除所有相关的app
    public void removePackage(String packageName) {
        final List<SimpleApplicationInfo> data = this.data;
        for (int i = data.size() - 1; i >= 0; i--) {
        	SimpleApplicationInfo info = data.get(i);
            final ComponentName component = info.intent.getComponent();
            if (packageName.equals(component.getPackageName())) {
                removed.add(info);
                data.remove(i);
            }
        }
        // This is more aggressive than it needs to be.
        mIconCache.flush();
    }
    
    // 当包名已更新时添加和删除相关icon
    public void updatePackage(Context context, String packageName) {
        final List<ResolveInfo> matches = findActivitiesForPackage(context, packageName);
        if (matches.size() > 0) {
            // Find disabled/removed activities and remove them from data and add them
            // to the removed list.
            for (int i = data.size() - 1; i >= 0; i--) {
                final SimpleApplicationInfo applicationInfo = data.get(i);
                final ComponentName component = applicationInfo.intent.getComponent();
                if (packageName.equals(component.getPackageName())) {
                    if (!findActivity(matches, component)) {
                        removed.add(applicationInfo);
                        mIconCache.remove(component);
                        data.remove(i);
                    }
                }
            }

            // Find enabled activities and add them to the adapter
            // Also updates existing activities with new labels/icons
            int count = matches.size();
            for (int i = 0; i < count; i++) {
                final ResolveInfo info = matches.get(i);
                SimpleApplicationInfo applicationInfo = findApplicationInfoLocked(
                        info.activityInfo.applicationInfo.packageName,
                        info.activityInfo.name);
                if (applicationInfo == null) {
                	//refreshDelShortcut(data, info.activityInfo.applicationInfo.packageName, info, context);
                	
                    //add(new SimpleApplicationInfo(info, mIconCache));
                	add(new SimpleApplicationInfo(context.getPackageManager(), info, mIconCache, null));
                } else {
                	mIconCache.remove(applicationInfo.componentName);
                	//mIconCache.getTitleAndIcon(applicationInfo, info);
                	mIconCache.getTitleAndIcon(applicationInfo, info, null);
                    modified.add(applicationInfo);
                    
                    //SimpleLauncherModel.updateItemInDatabaseHelper(context, new ContentValues(), applicationInfo);
                }
            }
        } else {
            // Remove all data for this package.
            for (int i = data.size() - 1; i >= 0; i--) {
                final SimpleApplicationInfo applicationInfo = data.get(i);
                final ComponentName component = applicationInfo.intent.getComponent();
                if (packageName.equals(component.getPackageName())) {
                    removed.add(applicationInfo);
                    mIconCache.remove(component);
                    data.remove(i);
                }
            }
        }
        
        dumpUpdateData();
    }
    
	public void dumpUpdateData()
	{
		for (int i = 0; i < added.size(); i++){
			SimpleApplicationInfo app = (SimpleApplicationInfo) added.get(i);
			Log.i(TAG, "SimpleAllAppsList added app.title " + app.title);
		}
		for (int j = 0; j < modified.size(); j++){
			SimpleApplicationInfo app = (SimpleApplicationInfo) modified.get(j);
			Log.i(TAG, "SimpleAllAppsList modified app.title " + app.title);
		}
		for (int k = 0; k < removed.size(); k++){
			SimpleApplicationInfo app = (SimpleApplicationInfo) removed.get(k);
			Log.i(TAG, "SimpleAllAppsList removed app.title " + app.title);
		}
	}
}
